package com.src.xyzk_personal.UpApp;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.src.tsdl_personal.R;
import com.src.xyzk_personal.config.Common;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Enumeration;


public class UpdateApp {
    private final static String TAG = "UpdateApp";


    ProgressBar pb;
    private ThreadUpdate m_thread = null;

    private boolean m_threadstart = false;
    private Activity activity = null;
    private int width = 0;
    private ViewGroup alertViewGroup;
    private Dialog alertDialog;

    private Button m_onclose;

    private Button m_onClinkOk;

    private Button m_onClinkNo;

    private String savePath;

    private String fileName;

    int fileSize;
    int downLoadFileSize;
    private boolean update_status = true;


    public UpdateApp(final Activity activity) {
        this.activity = activity;
        WindowManager manager = activity.getWindowManager();
        Display display = manager.getDefaultDisplay();
        width = display.getWidth() - 30;
        LayoutInflater inflater = activity.getLayoutInflater();
        alertViewGroup = (ViewGroup) inflater.inflate(R.layout.update_app_dialog, null);
        alertDialog = new Dialog(activity);
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alertDialog.show();

        m_onclose = (Button) alertViewGroup.findViewById(R.id.update_app_close);
        m_onclose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO 将取消点击状态填入缓存
                alertDialog.cancel();
                Common.dialog_isok = true;
            }
        });
        //显示版本信息
        final TextView input_vin_context = (TextView) alertViewGroup.findViewById(R.id.input_vin_context);
        input_vin_context.setText(Common.appNote);

        pb = (ProgressBar) alertViewGroup.findViewById(R.id.progressBar);

        m_onClinkOk = (Button) alertViewGroup.findViewById(R.id.update_app_but_ok);
        m_onClinkOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Common.downStatus) {  //按钮下载时
                    Common.downStatus = false;
                    m_onClinkOk.setText("取消下载");
                    savePath = "/storage/emulated/0/EOL_DOWNLINE";//下载安装路径
                    fileName = Common.FileName;
                    //显示下载进度条 关闭退出按钮
                    pb.setVisibility(View.VISIBLE);
                    m_onclose.setVisibility(View.INVISIBLE);
//                    SharedPreferences settings = activity.getSharedPreferences("EOL_wanda", Context.MODE_PRIVATE);
//                    //3.生成一个保存编辑变量
//                    SharedPreferences.Editor editor = settings.edit();
//                    editor.putBoolean("softStatus",true);
//                    //步骤4：提交
//                    editor.commit();
                    input_vin_context.setText("正在下载");
                    //启动下载线程    todo
                    StartThread(savePath, fileName);
                    Common.dialog_isok = true;
                } else { //按钮取消时
                    Common.downStatus = true;
                    m_onClinkOk.setText("下载");
                    //关闭进度条 显示关闭按钮
                    pb.setVisibility(View.INVISIBLE);
                    m_onclose.setVisibility(View.VISIBLE);
//                    SharedPreferences settings = activity.getSharedPreferences("EOL_wanda", Context.MODE_PRIVATE);
//                    //3.生成一个保存编辑变量
//                    SharedPreferences.Editor editor = settings.edit();
//                    editor.putBoolean("softStatus",false);
//                    //步骤4：提交
//                    editor.commit();
                    update_status = false;
                    alertDialog.cancel();
                    Common.dialog_isok = true;
                }
            }
        });
        //屏蔽返回
        alertDialog.setCancelable(false);

    }


    /**
     * 启动线程
     */
    public void StartThread(String Name, String Id) {
        m_thread = new ThreadUpdate(Name, Id);
        if (Common.Debug) Log.i(TAG, "     ߳ ...");
        m_threadstart = true;
        m_thread.start();
    }

    /**
     * 下载文件线程
     */
    public class ThreadUpdate extends Thread {
        private String projectName = null;
        private String androidId = null;

        public ThreadUpdate(String Name, String Id) {
            projectName = Name;
            androidId = Id;
        }

        @Override
        public void run() {
            String input = sendGetBufferedReader(Common.web_API_AppUpdate, Common.resource, savePath + "/" + fileName);
            if (update_status) {
                //对压缩包进行解压

                unzip(savePath + "/" + fileName, String.valueOf(Environment.getExternalStorageDirectory()));

                //删除压缩包
                deletezip(savePath + "/" + fileName);
                //删除其他版本的apk目录
                deletezip(Common.saveApkPath);
                //apk换位置
                String oldapkPath = Environment.getExternalStorageDirectory() + "/" + Common.ProjectName + "_" + Common.appVersion + ".apk";//apk解压后的位置
                String saveApkPath = Common.saveApkPath + Common.ProjectName + "_" + Common.appVersion + ".apk";//apk移动后的位置
                MoveApk(oldapkPath, saveApkPath);
                //关闭界面
                alertDialog.cancel();
                //唤起apk安装
                installApk(saveApkPath);
            }

        }
    }


    public void show() {
        alertDialog.getWindow().setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);
        alertDialog.getWindow().setContentView(alertViewGroup);
    }

    //apk换位置
    private void MoveApk(String oldApkPath, String apkPath) {
        File oldPath = new File(oldApkPath);

        File newName = new File(apkPath);

        String pfile = newName.getParent();
        File pdir = new File(pfile);
        //创建父级目录
        if (!pdir.exists()) {
            pdir.mkdirs();
        } else {
            pdir.delete();
            pdir.mkdirs();
        }
        oldPath.renameTo(newName);
        //移动文件

    }

    //安装apk

    private void installApk(String apkPath) {

        //todo  apk位置
        File apkFile = new File(apkPath);
        if (!apkFile.exists()) {
            return;
        }
        Intent install_Intent = new Intent(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            install_Intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(activity, "com.src.xyzk_personal.fileprovider", apkFile);
            install_Intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            install_Intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            install_Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
//        install_Intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        install_Intent.setDataAndType(
//                Uri.parse("file://" + apkFile.toString()),
//                "application/vnd.android.package-archive");
        activity.startActivity(install_Intent);

    }

    /**
     * 删除文件
     */
    private static void deletezip(String zipFilePath) {
        File f = new File(zipFilePath);
        if (f.exists()) {
            f.delete();
        }
    }

    /**
     * 解压zip格式压缩包
     * zipFilePath  压缩包路径
     * descDir 保存路径
     */
    private static void unzip(String zipFilePath, String descDir) {
        BufferedInputStream bi;
        BufferedOutputStream bos;
        ZipFile zf = null;
        try {
            zf = new ZipFile(zipFilePath, "GBK");
            Enumeration e = zf.getEntries();
            while (e.hasMoreElements()) {
                ZipEntry ze2 = (ZipEntry) e.nextElement();
                String entryName = ze2.getName();
                String path = descDir + "/" + entryName;
                if (ze2.isDirectory()) {
                    System.out.println("正在创建解压目录 - " + entryName);
                    File decompressDirFile = new File(path);
                    if (!decompressDirFile.exists()) {
                        decompressDirFile.mkdirs();
                    }
                } else {
                    System.out.println("正在创建解压文件 - " + entryName);
                    String fileDir = path.substring(0, path.lastIndexOf("/"));
                    File fileDirFile = new File(fileDir);
                    if (!fileDirFile.exists()) {
                        fileDirFile.mkdirs();
                    }
                    bos = new BufferedOutputStream(new FileOutputStream(descDir + "/" + entryName));
                    bi = new BufferedInputStream(zf.getInputStream(ze2));
                    byte[] readContent = new byte[1024];
                    int readCount = bi.read(readContent);
                    while (readCount != -1) {
                        bos.write(readContent, 0, readCount);
                        readCount = bi.read(readContent);
                    }
                    bos.close();
                }
            }
            zf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用get方式下载文件
     */

    public String sendGetBufferedReader(String url, String param, String savePath) {
        String result = "";
        FileOutputStream output = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开网络连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            HttpURLConnection connection1 = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            //设置超时时间和读写超时时间
            connection.setConnectTimeout(80000);
            connection.setReadTimeout(50000);
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.connect();
            int size = connection.getContentLength();
            int statuscode = connection.getResponseCode();
            if (statuscode == 200) {
                InputStream input = connection.getInputStream();
                File file = null;
                file = new File(savePath);
                output = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                downLoadFileSize = 0;
                InputStream input1 = connection1.getInputStream();
                int len;
                while ((len = input1.read(buffer)) > 0) {
                    this.fileSize += len;
                }
                sendMsg(0);

                int j = 0;
                while ((j = input.read(buffer)) != -1 && update_status) {

                    output.write(buffer, 0, j);
                    downLoadFileSize += j;
                    sendMsg(1);//更新进度条
                    output.flush();
                }
                sendMsg(2);//通知下载完成
            }
        } catch (Exception e) {
            System.out.println("使用get方式获取下载文件异常" + e);
            e.printStackTrace();
        }
        // 关闭流
        finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    //在线程中向Handler发送文件的下载量，进行UI界面的更新
    private void sendMsg(int i) {
        Message msg = new Message();
        msg.what = i;
        handler.sendMessage(msg);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {//定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        pb.setMax(fileSize);
                    case 1:
                        pb.setProgress(downLoadFileSize);
                        break;
                    case 2:
                        alertDialog.cancel();
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };
}

